package net.anzix.jhacks.flexclipse.decorator;

import net.anzix.jhacks.flexclipse.Activator;
import net.anzix.jhacks.flexclipse.builder.FlexclipseBuilder;

import org.eclipse.core.resources.ICommand;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.content.IContentDescription;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.IDecoration;
import org.eclipse.jface.viewers.ILightweightLabelDecorator;
import org.eclipse.jface.viewers.LabelProvider;

/**
 * Decorates Flex projects with a Fx suffix.
 * @author kocka
 *
 */
public class FlexclipseDecorator extends LabelProvider implements
		ILightweightLabelDecorator {

	private static final ImageDescriptor fxImage = Activator.getImageDescriptor("/icons/Fx_decorator.gif");

	public void decorate(Object element, IDecoration decoration) {
		if(isFlexProject(element)) {
			decoration.addOverlay(fxImage, IDecoration.BOTTOM_RIGHT);
		} else if (isFlexSourceFile(element)) {
			decoration.addOverlay(fxImage, IDecoration.BOTTOM_RIGHT);
		}
	}

	private boolean isFlexProject(Object element) {
			if (element instanceof IProject) {
				IProjectDescription description;
				try {
					description = ((IProject)element).getDescription();
				} catch (CoreException e) {
					return false;
				}
				for(ICommand cmd : description.getBuildSpec()) {
					if (FlexclipseBuilder.BUILDER_ID.equals(cmd.getBuilderName())) {
						return true;
					}
				}
			}
			return false;
	}

	private boolean isFlexSourceFile(Object element) {
		if (element instanceof IFile) {
			String contentType = null;
			try {
				final IContentDescription contentDescription = ((IFile)element).getContentDescription();
				if(contentDescription != null) {
					contentType = contentDescription.getContentType().getId();
				}
				if("net.anzix.jhacks.flexclipse.mxmlContentType".equals(contentType)) {
					return true;
				}
			} catch (CoreException e) {
				return false;
			}
		}
		return false;
}

	
}
